package com.xiaoming.project.core;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.Set;
import java.util.stream.Collectors;

public class ValidationTest {

    static void validatorObject(ValidateObject validateObject) {
        Validator validator = Validation.buildDefaultValidatorFactory()
                                        .getValidator();
        Set<ConstraintViolation<Object>> result = validator
                .validate(validateObject);

        if (result.isEmpty()) {
            return;
        }

        String message = result.stream().map(constrain -> constrain
                .getPropertyPath() + constrain.getMessage()).collect(
                Collectors.joining(System.lineSeparator()));
        System.out.println(message);
    }

    static class ValidateObject {

        @NotBlank
        private String name;

        @NotNull
        private Integer age;

        private ValidateObject(@NotBlank String name, @NotNull Integer age) {
            this.name = name;
            this.age = age;
        }

        public static ValidateObject valueOf(String name, Integer age) {
            return new ValidateObject(name, age);
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Integer getAge() {
            return age;
        }

        public void setAge(Integer age) {
            this.age = age;
        }

    }

}